<script setup>
import { ref, onMounted,watch,computed } from 'vue';
import { useUserStore } from '@/stores/user';
import { ElDialog, ElMessage, ElForm, ElFormItem, ElInput, ElButton } from 'element-plus';
import { addTeam,getTeamList,insertRef,joinTeam,getTeamRanking } from '@/api/user.js'

const userStore = useUserStore();
// 使用 store 中的数据
const userId = userStore.userId;
const userName = userStore.userName;

// 定义 refs 来存储比赛项目信息和队伍表单数据
const userList = ref([])
const collegeList = ref([])
const classList = ref([])
const refList = ref([])
const item = ref({});
const teamForm = ref({
  name: '',
  proId: '',
  number:''
});
const infor = ref({
  name:'',
  proId:''
})
const dialogVisible = ref(false); // 控制添加队伍对话框的可见性
const showRankingList = ref(false); 
const rankingList = ref([])

// 在组件挂载时从 localStorage 获取数据
onMounted(() => {
  const storedItem = JSON.parse(localStorage.getItem('selectedItem'));
  if (storedItem) {
    item.value = storedItem;
  }
  localStorage.removeItem('selectedItem');
  
  checkEventTime();  // 检查是否显示排名列表
});

watch(
  () => item.value.projectId,
  (newProjectId) => {
    if (newProjectId) {
      list();  
    }
  }
);

// 检查比赛时间是否在当前时间之前
const checkEventTime = () => {
  const eventTime = new Date(item.value.eventTime).getTime();
  const currentTime = new Date().getTime();
  
  if (currentTime > eventTime) {
    showRankingList.value = true;  // 本地时间晚于 eventTime，显示排名列表
  } else {
    showRankingList.value = false; // 本地时间早于 eventTime，不显示排名列表
  }
};

// 获取参赛人员名单
const list = async () => {
  try {
    const resp = await getTeamList(item.value.projectId);  // 使用 item.value.projectId
    const response = await getTeamRanking(item.value.projectId)
    rankingList.value = response.data
    console.log(rankingList.value)
    if (Array.isArray(resp.data.userList)) {  // 检查 resp.data.userList 是否为数组
      userList.value = resp.data.userList;  // 如果是数组，直接赋值给 userList
      collegeList.value = resp.data.collegeList
      classList.value = resp.data.classList
      refList.value = resp.data.refList
      console.log(collegeList.value)
      console.log(classList.value)
      console.log(refList.value)
      console.log(userList.value)
    } else {
      console.error("返回的数据不是数组", resp.data.userList);
      ElMessage.error("获取名单失败，返回的数据格式不正确");
    }
    console.log(userList.value);
    ElMessage.success("获取名单成功");
  } catch (error) {
    ElMessage.error("获取数据失败");
  }
};


// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 处理添加新队伍
const handleAddTeam = async () => {

  const isAlreadyInTeam = userList.value.some(user => user.username === userName);

if (isAlreadyInTeam) {
  // 如果用户已经在队伍中，弹出提示信息
  ElMessage.warning("您已经参赛，无法再次添加队伍");
  return; // 阻止继续执行
}

  try {
    // 将 item 中的 projectId 赋值给 teamForm 的 projectId
    teamForm.value.proId = item.value.projectId;
    teamForm.value.number = item.value.upnum;

    // 传递表单数据和项目ID
    await addTeam(userId,teamForm.value );
    ElMessage.success('队伍添加成功');
    dialogVisible.value = false; // 添加成功后关闭对话框
    console.log(teamForm.value)
    list()

    // 重置表单字段
    teamForm.value.name = '';
    teamForm.value.proId = '';
    teamForm.value.number = '';
  } catch (error) {
    ElMessage.error('队伍以达到最大上限');
    teamForm.value.name = '';
    teamForm.value.proId = '';
    teamForm.value.number = '';
  }
};

// 处理分组
const groupedUsers = computed(() => {
  const groups = {};
  userList.value.forEach(user => {
    const tname = user.tname || '未分组';
    if (!groups[tname]) {
      groups[tname] = { tname, users: [] };
    }
    groups[tname].users.push(user);
  });
  return Object.values(groups);
});

//申请裁判
const handleCancel = async () => {

  // 检查用户是否已经在队伍中
  const isAlreadyInTeam = userList.value.some(user => user.username === userName);
  const isAlreadyReferee = refList.value.some(ref => ref.username === userName);

  if (isAlreadyInTeam || isAlreadyReferee) {
    // 如果用户已经在队伍中，弹出提示信息
    ElMessage.warning("您报名当前赛事，请勿重复报名");
    return;  // 阻止继续执行
  }

  try {
    await insertRef(item.value,userId)
    ElMessage.success("申请成功，请准时到达场地")
    list()
  } catch (error) {
    ElMessage.error("裁判已足够")
  }
}

//进入队伍
const handleJoinTeam = async (group) => {
  console.log("进入 handleJoinTeam 方法", group); // 检查是否被调用
  
  // 检查用户是否已经在队伍中
  const isAlreadyInTeam = group.users.some(user => user.username === userName);
  const isAlreadyReferee = refList.value.some(ref => ref.username === userName);

  if (isAlreadyInTeam || isAlreadyReferee) {
    // 如果用户已经在队伍中，弹出提示信息
    ElMessage.warning("您报名当前赛事，请勿重复报名");
    return;  // 阻止继续执行
  }

  try {
    infor.value.proId = item.value.projectId; // 项目 ID
    infor.value.name = group.tname; // 队伍名称
    console.log(infor.value); // 打印 infor.value
    console.log(userId)
    await joinTeam(userId, infor.value); // 调用加入队伍的 API
    ElMessage.success("成功加入队伍");
    list(); // 更新队伍列表
  } catch (error) {
    ElMessage.error("加入队伍失败，请重试");
  }
};

</script>

<template>
  <el-card class="box-card" shadow="hover">
    <h2 style="text-align: center; margin-bottom: 20px;">比赛信息</h2>

    <el-descriptions bordered column={1} class="description-box">
      <el-descriptions-item label="项目名称：">{{ item.name }}</el-descriptions-item>
      <el-descriptions-item label="项目编号：">{{ item.number }}</el-descriptions-item>
      <el-descriptions-item label="规则介绍：">{{ item.introduction }}</el-descriptions-item>
      <el-descriptions-item label="比赛类型：">{{ item.type == 0 ? '个人赛' : '团体赛' }}</el-descriptions-item>
      <el-descriptions-item label="男子/女子：">{{ item.gtype === 0 ? '女子' : '男子' }}</el-descriptions-item>
      <el-descriptions-item label="比赛地点：">{{ item.place }}</el-descriptions-item>
      <el-descriptions-item label="比赛时间：">{{ formatDate(item.eventTime) }}</el-descriptions-item>
      <el-descriptions-item label="招收队伍：">{{ item.upnum }} 队</el-descriptions-item>
      <el-descriptions-item label="招收裁判员：">{{ item.renum }} 人</el-descriptions-item>
      <el-descriptions-item label="报名时间：">{{ formatDate(item.startTime) }} -- {{ formatDate(item.endTime) }}</el-descriptions-item>
      <el-descriptions-item>欢迎大家踊跃报名！</el-descriptions-item>
    </el-descriptions>

    <!-- 添加队伍按钮 -->
    <!-- <div style="text-align: center; margin: 20px;">
      <el-button type="primary" @click="dialogVisible = true">添加队伍</el-button>
      <el-button type="primary" @click="handleCancel">裁判申请</el-button>
    </div> -->
    <div class="actions" style="text-align: center; margin-top: 20px;">
      <el-button
          type="primary"
          @click="dialogVisible = true"
          :disabled="item.status !== 1"
          :style="{ cursor: item.status === 1 ? 'pointer' : 'not-allowed' }">
        添加队伍
      </el-button>
      <el-button
          type="danger"
          @click="handleCancel"
          :disabled="item.status !== 1"
          :style="{ cursor: item.status === 1 ? 'pointer' : 'not-allowed' }">
        申请裁判
      </el-button>
    </div>

    <!-- 队伍列表 -->
    <div v-for="group in groupedUsers" :key="group.tname" style="margin-top: 30px;">
      <el-card class="participant-card" shadow="hover">
        <h3 style="text-align: center; margin-bottom: 15px;">{{ group.tname }} 组参赛人员列表</h3>
        <el-table :data="group.users" stripe style="width: 100%">
          <el-table-column prop="username" label="姓名" width="200"></el-table-column>

          <!-- 显示学院名称 -->
          <el-table-column label="学院" width="200">
            <template #default="scope">
              <span>
                <span v-for="college in collegeList" :key="college.collegeId">
                  {{ college.collegeId === scope.row.collegeId ? college.name : '' }}
                </span>
              </span>
            </template>
          </el-table-column>

          <!-- 显示班级名称 -->
          <el-table-column label="班级" width="150">
            <template #default="scope">
              <span>
                <span v-for="classItem in classList" :key="classItem.classId">
                  {{ classItem.classId === scope.row.classId ? classItem.name : '' }}
                </span>
              </span>
            </template>
          </el-table-column>
        </el-table>


        <div style="text-align: center; margin-top: 10px;">
          <el-button type="success" @click="handleJoinTeam(group)">加入该队伍</el-button>
        </div>

        
      </el-card>
    </div>

    <!-- 裁判列表 -->
    <el-card class="participant-card" shadow="hover" style="margin-top: 30px;">
      <h3 style="text-align: center; margin-bottom: 15px;">裁判员列表</h3>
      <el-table :data="refList" stripe style="width: 100%">
        <el-table-column prop="username" label="姓名" width="200"></el-table-column>

        <!-- 显示学院名称 -->
        <el-table-column label="学院" width="200">
          <template #default="scope">
            <span>
              <span v-for="college in collegeList" :key="college.collegeId">
                {{ college.collegeId === scope.row.collegeId ? college.name : '' }}
              </span>
            </span>
          </template>
        </el-table-column>

        <!-- 显示班级名称 -->
        <el-table-column label="班级" width="150">
          <template #default="scope">
            <span>
              <span v-for="classItem in classList" :key="classItem.classId">
                {{ classItem.classId === scope.row.classId ? classItem.name : '' }}
              </span>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 排名列表 -->
    <el-card v-if="showRankingList" class="participant-card" shadow="hover" style="margin-top: 30px;">
      <h3 style="text-align: center; margin-bottom: 15px;">排名列表</h3>
      <el-table :data="rankingList" stripe style="width: 100%">
        <el-table-column prop="tname" label="团队名" width="200"></el-table-column>
        <el-table-column prop="result" label="结果" width="100"></el-table-column>
        <el-table-column prop="score" label="成绩" width="90"></el-table-column>
        <el-table-column prop="rank" label="排名" width="100"></el-table-column>
      </el-table>
    </el-card>

    <!-- 添加队伍的弹窗 -->
    <el-dialog title="添加队伍" v-model="dialogVisible" style="width: 500px;">
      <el-form :model="teamForm">
        <el-form-item label="队伍名称" required>
          <el-input v-model="teamForm.name" placeholder="请输入队伍名称"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddTeam">提交</el-button>
      </div>
    </el-dialog>




  </el-card>
</template>

<style lang="scss" scoped>
.box-card {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
}

.description-box {
  background-color: #fff;
  padding: 15px;
  border-radius: 10px;
}
.actions {
  display: flex;
  justify-content: space-around;
}

.el-descriptions__label {
  font-weight: bold;
}

.el-button {
  width: 120px;
}
</style>
